<template>
  <view class="content">
    <van-nav-bar title="发布" left-text="" :left-arrow="true" placeholder fixed @click-left="onClickLeft" />
    <view class="public" :style="{ height: `calc(100vh - 250rpx - ${safeAreaTop}px)` }">
      <view class="public-list">
        <uni-easyinput
          class="public-cont"
          :inputBorder="false"
          type="textarea"
          v-model="formData.content"
          placeholder="请输入信息内容"
        ></uni-easyinput>
        <view class="file-upload">
          <view class="upload-list">
            <view class="list-item" v-for="(item, index) in formData.images" :key="item">
              <image class="img-box" :src="item" />
              <text class="del" @click="delHandle(index)"></text>
            </view>
          </view>
          <view class="upload">
            <view v-if="formData.images.length !== 9" @click="uploadHandle">
              <image class="img-box" src="https://images.tongzhuangkc.com/camera.png" />
              <text>添加图片</text>
            </view>
          </view>
        </view>
      </view>
      <view class="public-form">
        <template v-if="formData.goods_type == 1">
          <view class="title">货品类型</view>
          <uni-data-checkbox
            v-model="formData.is_whole"
            :localdata="wholeList"
            :clearable="false"
            :map="{ text: 'name', value: 'value' }"
          ></uni-data-checkbox>
        </template>
        <view style="margin: 0 -32rpx">
          <van-cell title="商品分类" is-link @click="isShow = true" :value="classify.label" />
        </view>
        <template v-if="formData.goods_type == 1">
          <view class="form-item">
            <view class="item-list">
              <text>全清数量</text>
              <uni-easyinput
                :inputBorder="false"
                type="number"
                min="0"
                :clearable="false"
                v-model="formData.wholesale_num"
                placeholder=""
              ></uni-easyinput>
            </view>
            <view class="item-list">
              <text>全清价格</text>
              <uni-easyinput
                :inputBorder="false"
                type="text"
                min="0"
                :clearable="false"
                v-model="formData.wholesale_price"
                placeholder=""
              ></uni-easyinput>
            </view>
          </view>
          <view class="form-item">
            <view class="item-list">
              <text>起批量</text>
              <uni-easyinput
                :inputBorder="false"
                :clearable="false"
                type="number"
                min="0"
                v-model="formData.sale_num"
                placeholder=""
              ></uni-easyinput>
            </view>
            <view class="item-list">
              <text>起批价</text>
              <uni-easyinput
                :inputBorder="false"
                type="text"
                min="0"
                :clearable="false"
                v-model="formData.sale_price"
                placeholder=""
              ></uni-easyinput>
            </view>
          </view>
        </template>
      </view>
      <template v-if="formData.goods_type == 1">
        <view class="public-form">
          <view class="title">属性标签</view>
          <uni-data-checkbox
            v-model="formData.age_type"
            :localdata="ageList"
            :map="{ text: 'name', value: 'value' }"
          ></uni-data-checkbox>
          <view class="checkbox">
            <view
              class="checkbox-list"
              :class="formData.tag_id.includes(item.value) ? 'active' : ''"
              v-for="item in tagList"
              :key="item.value"
              @click="chooseTag(item.value)"
              >{{ item.name }}</view
            >
          </view>
        </view>
      </template>
      <view class="public-form">
        <view class="form-item">
          <text>电话</text>
          <uni-easyinput
            :inputBorder="false"
            type="number"
            :clearable="false"
            v-model="formData.contact_mobile"
            placeholder=""
          ></uni-easyinput>
        </view>
        <view class="form-item">
          <text>微信号</text>
          <uni-easyinput
            :inputBorder="false"
            type="number"
            :clearable="false"
            v-model="formData.contact_wx_code"
            placeholder=""
          ></uni-easyinput>
          <text>同手机号</text><van-switch size="15" @change="changeWitch" :checked="checked" />
        </view>
        <view style="margin: 0 -32rpx">
          <van-cell title="地理位置" :value="formData.address" @click="addressShow = true">
            <template #right-icon>
              <image class="img-box" src="https://images.tongzhuangkc.com/location.png" alt="" />
            </template>
          </van-cell>
        </view>
      </view>
      <view class="agreement">
        <van-checkbox :value="checkedBox" @change="checkedBox = !checkedBox" shape="square">
          我已阅读并同意<text class="agreement-text" @click="goPage">《发布协议》</text>
        </van-checkbox>
      </view>
      <view
        class="public-option"
        :style="{
          paddingBottom: safeAreaBot + 'px',
        }"
      >
        <view class="public-btn" @click="submitHandle">立即发布</view>
      </view>
    </view>
    <m-picker
      mode="bottom"
      :show.sync="isShow"
      :range="[classifyList]"
      @cancel="isShow = false"
      @confirm="confirmHandle"
    ></m-picker>
    <pickerAddress :value="addressShow" @confirm="addresspick" />
  </view>
</template>

<script>
import { reactive, toRefs, onMounted } from 'vue'
import { getDetail, getContact, save } from '@/http/publish'
import { uploadImageToQiniu } from '@/utils/upload'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user'
import mPicker from '@/components/jarvis-picker/m-picker.vue'
import pickerAddress from '@/components/liudx-pickerAddress/index.vue'
export default {
  components: { mPicker, pickerAddress },
  setup() {
    const userStore = useUserStore()
    const state = reactive({
      isShow: false,
      addressShow: false,
      wholeList: [],
      classifyList: [],
      ageList: [],
      tagList: [],
      checked: false,
      checkedBox: false,
      isIpx: false,
      safeAreaTop: 0,
      safeAreaBot: 0,
      classify: {
        label: '',
        value: '',
      },
      formData: {
        goods_id: '',
        content: '',
        goods_type: 1,
        classify: '',
        images: [],
        is_whole: 1,
        age_type: 1,
        tag_id: [],
        wholesale_num: '',
        wholesale_price: '',
        sale_num: '',
        sale_price: '',
        contact_mobile: '',
        contact_wx_code: '',
        province: '',
        city: '',
        region: '',
        address: '',
      },
    })
    const onClickLeft = () => {
      uni.navigateBack({
        delta: 1,
      })
    }
    onMounted(() => {
      uni.getSystemInfo({
        success: function (res) {
          state.safeAreaTop = res.safeAreaInsets.top === 20 ? 0 : res.safeAreaInsets.top
          state.safeAreaBot = res.safeAreaInsets.bottom !== 0 ? res.safeAreaInsets.bottom : '20'
        },
      })
    })
    onShow(() => {
      state.classifyList = []
      const { classify, is_whole, age_type, tag_id } = userStore.getField()
      classify.forEach((item) => {
        state.classifyList.push({
          label: item.name,
          value: item.id,
        })
      })
      state.wholeList = is_whole
      state.ageList = age_type
      state.tagList = tag_id
    })
    onLoad((e) => {
      if (e.id) {
        getGoods(e.id)
      } else {
        state.formData.goods_type = e.type
        getContactHandle()
      }
    })
    const getGoods = async (goods_id) => {
      const { data } = await getDetail({ goods_id })
      for (let key in state.formData) {
        state.formData[key] = data[key]
      }
      state.classifyList.forEach((item) => {
        if (item.value == data.classify) {
          state.classify = item
        }
      })
    }
    const goPage = () => {
      uni.navigateTo({
        url: `/subpackage-agreement/release/index`,
      })
    }
    const chooseTag = (id) => {
      if (state.formData.tag_id.includes(id)) {
        state.formData.tag_id = state.formData.tag_id.filter((item) => item !== id)
      } else {
        state.formData.tag_id.push(id)
      }
    }
    const uploadHandle = () => {
      uni.chooseImage({
        count: 9 - state.formData.images.length,
        sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有
        success: (res) => {
          if (res.tempFiles) {
            res.tempFiles.forEach(async (item) => {
              const data = await uploadImageToQiniu(item)
              state.formData.images.push(`https://images.tongzhuangkc.com/${data.hash}`)
            })
          }
        },
      })
    }
    const delHandle = (index) => {
      state.formData.images.splice(index, 1)
    }
    const confirmHandle = (e) => {
      state.classify = state.classifyList[e[0]]
      state.formData.classify = state.classify.value
      state.isShow = false
    }
    const addresspick = (obj) => {
      state.formData.address = ''
      let arr = ['province', 'city', 'region']
      arr.map((key) => {
        state.formData[key] = obj[key].value
        if (key === 'region') {
          state.formData.address += obj[key].name
        } else {
          state.formData.address += obj[key].name + '-'
        }
      })
      state.addressShow = false
    }
    const changeWitch = () => {
      state.checked = !state.checked
      if (state.checked) {
        state.formData.contact_wx_code = state.formData.contact_mobile
      }
    }
    const getContactHandle = async () => {
      const { data } = await getContact()
      state.formData.contact_mobile = data.contact_mobile
      state.formData.contact_wx_code = data.contact_wx_code
    }
    const submitHandle = async () => {
      if (!state.formData.content) {
        uni.showToast({
          title: '请输入信息内容',
          icon: 'none',
        })
        return
      }
      if (!state.formData.images.length) {
        uni.showToast({
          title: '请上传商品图片',
          icon: 'none',
        })
        return
      }
      if (!state.formData.classify) {
        uni.showToast({
          title: '请选择商品分类',
          icon: 'none',
        })
        return
      }
      if (!state.checkedBox) {
        uni.showToast({
          title: '请阅读并勾选发布协议',
          icon: 'none',
        })
        return
      }
      const { data } = await save(state.formData)

      if (data.msg) {
        uni.showToast({
          title: data.msg,
          icon: 'none',
        })
      }

      setTimeout(() => {
        uni.switchTab({
          url: `/pages/home/index`,
        })
      }, 1000)
    }
    return {
      ...toRefs(state),
      onClickLeft,
      getGoods,
      goPage,
      chooseTag,
      uploadHandle,
      delHandle,
      confirmHandle,
      addresspick,
      changeWitch,
      submitHandle,
    }
  },
}
</script>

<style lang="scss">
.content {
  height: 100vh;
}
.public {
  height: calc(100vh - 230rpx);
  overflow-y: auto;
}
.public-list {
  background: #fff;
  padding-bottom: 32rpx;
  margin-bottom: 16rpx;
  .uni-easyinput__content {
    padding: 0 24rpx;
    height: 240rpx;
  }
}
.public-form {
  background: #fff;
  margin-bottom: 16rpx;
  padding: 32rpx 24rpx;
  overflow: hidden;
  .form-item {
    display: flex;
    align-items: center;
    text {
      width: 160rpx;
      font-size: 32rpx;
      color: #2b303b;
    }
    .item-list {
      width: 50%;
      display: flex;
      align-items: center;
      border-bottom: 2rpx solid #e7e7e7;
    }
  }
  .title {
    color: #000;
    font-size: 32rpx;
    margin-bottom: 24rpx;
  }
  .checkbox {
    display: flex;
    margin-top: 24rpx;
    &-list {
      width: 168rpx;
      height: 72rpx;
      font-size: 28rpx;
      border: 2rpx solid #eaeaea;
      text-align: center;
      line-height: 72rpx;
      margin-right: 10rpx;
      &.active {
        border-color: #3775f2;
        color: #3775f2;
        background: #e5eeff;
      }
    }
  }
  .img-box {
    width: 48rpx;
    height: 48rpx;
  }
  .switch-box {
    font-size: 28rpx;
    color: #7f8798;
    display: flex;
    align-items: center;
    text {
      margin-right: 10rpx;
    }
  }
  .checklist-text,
  .van-cell {
    font-size: 32rpx !important;
    color: #140f08 !important;
  }
}
.agreement {
  padding: 16rpx 32rpx;
  color: #2b303b;
  font-size: 28rpx;
  &-text {
    color: #3775f2;
  }
}
.public-option {
  padding: 16rpx 0 16rpx;
  width: 100%;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  .public-btn {
    height: 80rpx;
    background: linear-gradient(90deg, #38acff 0%, #387bff 100%);
    box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(56, 122, 255, 0.4);
    border-radius: 40rpx;
    color: #fff;
    text-align: center;
    line-height: 80rpx;
    font-size: 28rpx;
  }
}
.upload-list {
  display: flex;
  flex-wrap: wrap;
  .list-item {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    margin: 0 15rpx 15rpx 0;

    .img-box {
      width: 100%;
      height: 100%;
      border-radius: 20rpx;
    }
    .del {
      width: 30rpx;
      height: 30rpx;
      background: url('https://images.tongzhuangkc.com/tz/del-icon.png') no-repeat;
      background-size: 100% 100%;
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}
.file-upload {
  padding: 0 32rpx;
  .upload {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-flow: wrap;
    height: 176rpx;
    background: #f5f6fa;
    border-radius: 16rpx;
    .img-box {
      display: block;
      margin: 0 auto;
      width: 64rpx;
      height: 64rpx;
    }
    text {
      display: block;
      width: 100%;
      text-align: center;
      font-size: 32rpx;
      color: #2b303b;
    }
  }
}
</style>
